package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import com.sky.vo.UserReportVO;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {

        String openid = getOpenID(userLoginDTO);

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(!StringUtils.hasLength(openid)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        String jwt="";
        //判断是否是新用户,如果是新用户，自动完成注册
        UserLoginVO userLoginVO = new UserLoginVO();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid,openid);
        User user = this.getOne(queryWrapper);
        if(user==null){
            User newUser = new User();
            newUser.setOpenid(openid);
            newUser.setCreateTime(LocalDateTime.now());
            this.save(newUser);
            jwt = createJWT(newUser);
            userLoginVO.setId(newUser.getId());
        }else {
            jwt=createJWT(user);
            userLoginVO.setId(user.getId());
        }
        userLoginVO.setToken(jwt);
        userLoginVO.setOpenid(openid);

        return userLoginVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList=new ArrayList<>();
        localDateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            localDateList.add(begin);
        }
        List<Long> totalUserList=new ArrayList<>();
        List<Long> newUserList=new ArrayList<>();
        for (LocalDate date : localDateList) {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            userLambdaQueryWrapper.lt(User::getCreateTime,endTime);
            long totalUser = this.count(userLambdaQueryWrapper);
            userLambdaQueryWrapper.gt(User::getCreateTime,beginTime);
            long newUser = this.count(userLambdaQueryWrapper);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .newUserList(org.apache.commons.lang.StringUtils.join(newUserList,","))
                .dateList(org.apache.commons.lang.StringUtils.join(localDateList,","))
                .totalUserList(org.apache.commons.lang.StringUtils.join(totalUserList,","))
                .build();
    }

    private String createJWT(User newUser) {
        Map<String, Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, newUser.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        return jwt;
    }

    private String getOpenID(UserLoginDTO userLoginDTO) {
        Map<String, String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        //拿出来的是json格式的字符串
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
